package com.haiyou.dc.thread.test1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 容器选择电影院位置
 */
public class HappyCinema2 {

    public static void main(String[] args) {

        List<Integer> availble = new ArrayList<>();
        availble.addAll(Arrays.asList(1, 3, 5, 6,7,8));

        List<Integer> seat1 = new ArrayList<>();
        seat1.addAll(Arrays.asList(1, 3));

        List<Integer> seat2 = new ArrayList<>();
        seat2.addAll(Arrays.asList(9, 7));

        Cinema2 c = new Cinema2(availble, "开心电影院");
        new Thread(new Cunstomer2(c, seat1), "张三").start();
        new Thread(new Cunstomer2(c, seat2), "李四").start();
    }
}

/**
 * 顾客
 */
class Cunstomer2 implements Runnable {

    private Cinema2 cinema;
    private List<Integer> seat;

    public Cunstomer2(Cinema2 cinema, List<Integer> seat) {
        this.cinema = cinema;
        this.seat = seat;
    }

    @Override
    public void run() {
        synchronized (cinema) {
            boolean flag = cinema.bookTicket(seat);
            if (flag) {
                System.out.println(Thread.currentThread().getName() + ",购票成功...." + seat);
            } else {
                System.out.println(Thread.currentThread().getName() + "购票失败....位置不够，购票数" + seat);
            }
        }

    }
}


/**
 * 影院
 */
class Cinema2 {
    private List<Integer> available;
    private String name;

    public Cinema2(List<Integer> available, String name) {
        this.available = available;
        this.name = name;
    }

    public boolean bookTicket(List<Integer> seat) {
        System.out.println("欢迎选购，" + this.name + ",可用位置" + available);
        //不能直接使用available
        List<Integer> copy = new ArrayList<>();
        copy.addAll(available);

        //相减，求差集
        copy.removeAll(seat);
        System.out.println(copy);

        //判断大小
        if (available.size() - copy.size() != seat.size()) {
            return false;
        }

        //成功
        available = copy;

        return true;
    }
}
